package com.aurora.leetcode.answer;


import com.aurora.leetcode.entity.ListNode;
import com.aurora.leetcode.util.MyUtils;

/**
 * @author : Aurora
 * @date : 2024/4/19 16:47
 * @description 给你单链表的头节点 head ，请你反转链表，并返回反转后的链表。
 */
public class ReverseList_206 {
    public ListNode reverseList(ListNode head) {
        if(head == null) return head;
        ListNode p = head;
        ListNode reverse = new ListNode();
        while(p != null){
            if(reverse == null){
                reverse.next = p;
            }else{
                ListNode temp = p;
                p = p.next;
                temp.next = reverse.next;
                reverse.next = temp;
            }
        }
        return reverse.next;
    }

    ListNode reverseHead = new ListNode();
    ListNode p = reverseHead;
    public ListNode recursion(ListNode head){
        if(head == null)return head;
        if(head.next != null){
            recursion(head.next);
        }
        p.next = head;
        p = head;
        p.next = null;
        return reverseHead.next;
    }

    public static void main(String[] args) {
        ReverseList_206 obj = new ReverseList_206();
        int[] arr = new int[]{1,2,3,4,5};
        ListNode listNode = MyUtils.constructListNode(arr);
        System.out.println("反转前的单链表");
        MyUtils.printLinkedList(listNode);
        System.out.println("反转后的单链表");
//        ListNode reverseList = obj.reverseList(listNode);
        ListNode reverseList = obj.recursion(listNode);
        MyUtils.printLinkedList(reverseList);
    }


}
